const path = require('path')
const WebpackScpPlugin = require('./plugins/webpack-scp-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const resolve = dir => {
    return path.join(__dirname, dir)
}
const config = {
    baseUrl: process.env.VUE_APP_PUBLIC_PATH,
    lintOnSave: false,
    productionSourceMap: false,
    css: {
        loaderOptions: {
            less: {
                javascriptEnabled: true
            }
        }
    },
    chainWebpack: config => {
        config.resolve.alias
            .set('vue$', 'vue/dist/vue.esm.js')
            .set('@', resolve('src'))
            .set('_c', resolve('src/components'))
        config.optimization
            .splitChunks({
                cacheGroups: {
                    vendor: { // 抽离第三方插件
                        test: /node_modules/, // 指定是node_modules下的第三方包
                        chunks: 'initial',
                        name: 'common/vendor', // 打包后的文件名，任意命名
                        priority: 10// 设置优先级，防止和自定义的公共代码提取时被覆盖，不进行打包
                    },
                    utils: { // 抽离自定义公共代码
                        test: /\.js$/,
                        chunks: 'initial',
                        name: 'common/utils',
                        minSize: 0// 只要超出0字节就生成一个新包
                    }
                }
            })
    },
    configureWebpack: {
        plugins: [
            new CopyWebpackPlugin([{
                from: path.resolve(__dirname, './static'),
                to: 'static', // static
                ignore: ['.*']
            }]),
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true// set to true if you want JS source maps
            })
        ]
    },
    devServer: {
        disableHostCheck: true,
        before: function (app) {
            if (!process.env.npm_config_proxydev) {
                app.use(require('connect-cgi-mock')({
                    root: resolve('mock'),
                    route: '/api'
                }))
            }
        }
    }
}

if (process.env.npm_config_proxydev) {
    config.devServer.proxy = {
        '/api': {
            target: 'http://n.szbatm.com',
            changeOrigin: true,
            logLevel: 'debug',
            pathRewrite: {
                '^/api': '/financial-manager'
            }
        }
    }
}

if (process.env.npm_config_deploy) {
    let options = {
        ip: process.env.VUE_APP_IP,
        port: process.env.VUE_APP_PORT,
        user: process.env.VUE_APP_USER,
        password: process.env.VUE_APP_PASSWORD,
        src: resolve(process.env.VUE_APP_SRC),
        dist: process.env.VUE_APP_DIST
    }
    config.configureWebpack.plugins.push(new WebpackScpPlugin(options))
}

module.exports = config
